<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['record:record:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['record:record:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['record:record:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['record:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="答题用户" align="center" prop="userId">
        <template #default="scope">
          {{ getUserNameById(scope.row.userId) }}
        </template>
      </el-table-column>
      <el-table-column label="题目" align="center" prop="questionId">
        <template #default="scope">
          {{ getQuestionNameById(scope.row.questionId) }}
        </template>
      </el-table-column>
      <el-table-column label="所属圈子" align="center" prop="circleId">
        <template #default="scope">
          {{ getCircleNameById(scope.row.circleId) }}
        </template>
      </el-table-column>
      <el-table-column label="用户答案" align="center" prop="userAnswer" />
      <el-table-column label="是否答对" align="center" prop="isCorrect" />
      <el-table-column label="获得积分数量" align="center" prop="pointsEarned" />
      <el-table-column label="答题时间" align="center" prop="answerTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.answerTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="答题用时(秒)" align="center" prop="timeSpent" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['record:record:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['record:record:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户答题记录管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="答题用户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择答题用户" clearable>
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.name"
              :value="Number(item.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题目" prop="questionId">
          <el-select v-model="form.questionId" placeholder="请选择题目" clearable>
            <el-option
              v-for="item in questionOptions"
              :key="item.id"
              :label="item.name"
              :value="Number(item.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属圈子" prop="circleId">
          <el-select v-model="form.circleId" placeholder="请选择所属圈子" clearable>
            <el-option
              v-for="item in circleOptions"
              :key="item.id"
              :label="item.name"
              :value="Number(item.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="用户答案" prop="userAnswer">
          <el-input v-model="form.userAnswer" placeholder="请输入用户答案" />
        </el-form-item>
        <el-form-item label="是否答对 0-错误 1-正确" prop="isCorrect">
          <el-input v-model="form.isCorrect" placeholder="请输入是否答对 0-错误 1-正确" />
        </el-form-item>
        <el-form-item label="获得积分数量" prop="pointsEarned">
          <el-input v-model="form.pointsEarned" placeholder="请输入获得积分数量" />
        </el-form-item>
        <el-form-item label="答题时间" prop="answerTime">
          <el-date-picker clearable
            v-model="form.answerTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择答题时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="答题用时(秒)" prop="timeSpent">
          <el-input v-model="form.timeSpent" placeholder="请输入答题用时(秒)" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Record">
import { listRecord, getRecord, delRecord, addRecord, updateRecord, listQuestion, listUser, listCircle } from "@/api/answerRecord/record";

const { proxy } = getCurrentInstance();

const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 添加选项列表数据
const userOptions = ref([]);
const questionOptions = ref([]);
const circleOptions = ref([]);

// 获取用户列表
function getUserList() {
  listUser().then(response => {
    if (response.code === 200 && response.rows) {
      userOptions.value = response.rows.map(item => ({
        id: String(item.userId),
        name: item.userName || `用户${item.userId}`
      }));
    } else {
      userOptions.value = [];
      proxy.$modal.msgError("获取用户列表失败");
    }
  }).catch(() => {
    userOptions.value = [];
    proxy.$modal.msgError("获取用户列表失败");
  });
}

// 获取题目列表
function getQuestionList() {
  listQuestion().then(response => {
    if (response.code === 200 && response.rows && Array.isArray(response.rows)) {
      questionOptions.value = response.rows.map(item => {
        const id = item.questionId || item.id || item.question_id;
        const name = item.questionTitle || item.title || item.question_title || item.name || `题目${id}`;
        return { id, name };
      }).filter(item => item.id);
    } else {
      questionOptions.value = [];
      proxy.$modal.msgError("获取题目列表失败");
    }
  }).catch(error => {
    questionOptions.value = [];
    proxy.$modal.msgError("获取题目列表失败");
  });
}

// 获取圈子列表
function getCircleList() {
  listCircle().then(response => {
    if (response.code === 200 && response.rows && Array.isArray(response.rows)) {
      circleOptions.value = response.rows.map(item => {
        const id = item.circleId || item.id || item.circle_id;
        const name = item.circleName || item.name || item.circle_name || item.title || `圈子${id}`;
        return { id, name };
      }).filter(item => item.id);
    } else {
      circleOptions.value = [];
      proxy.$modal.msgError("获取圈子列表失败");
    }
  }).catch(error => {
    circleOptions.value = [];
    proxy.$modal.msgError("获取圈子列表失败");
  });
}

// 获取用户名
function getUserNameById(id) {
  if (!id) return '';
  const user = userOptions.value.find(item => String(item.id) === String(id));
  return user ? user.name : `用户${id}`;
}

function getQuestionNameById(id) {
  if (!id) return '';
  const question = questionOptions.value.find(item => String(item.id) === String(id));
  return question ? question.name : `题目${id}`;
}

function getCircleNameById(id) {
  if (!id) return '';
  const circle = circleOptions.value.find(item => String(item.id) === String(id));
  return circle ? circle.name : `圈子${id}`;
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    questionId: null,
    circleId: null,
  },
  rules: {
    userId: [
      { required: true, message: "答题用户不能为空", trigger: "change" }
    ],
    questionId: [
      { required: true, message: "题目不能为空", trigger: "change" }
    ],
    circleId: [
      { required: true, message: "圈子不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户答题记录管理列表 */
function getList() {
  loading.value = true;
  listRecord(queryParams.value).then(response => {
    recordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 在组件挂载时获取所有列表
onMounted(() => {
  getUserList();
  getQuestionList();
  getCircleList();
});

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    recordCode: null,
    userId: null,
    questionId: null,
    circleId: null,
    userAnswer: null,
    isCorrect: null,
    pointsEarned: null,
    answerTime: null,
    timeSpent: null,
    createdBy: null,
    createdTime: null,
    updatedBy: null,
    updatedTime: null,
    deletedFlag: null
  };
  proxy.resetForm("recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户答题记录管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getRecord(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户答题记录管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除用户答题记录管理编号为"' + _ids + '"的数据项？').then(function() {
    return delRecord(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('record/record/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`)
}

getList();
</script>
